package com.lbb.config;

import com.lbb.io.Resources;
import com.lbb.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    //使用dom4j对配置文件进行解析
    public Configuration parse(InputStream inputStream) throws DocumentException, PropertyVetoException {
        //1.获取Document对象
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element root_element = document.getRootElement();
        //获取配置文件中的标签
        List<Element> list = root_element.selectNodes("//property");
        //利用Properties保存数据,以便接下来创建数据库连接池
        Properties properties = new Properties();
        for(Element e:list){
            String name = e.attributeValue("name");
            String value = e.attributeValue("value");
            properties.setProperty(name,value);
        }
        //利用c3p0创建数据库连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driver"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        //解析mapper.xml
        List<Element> element_mappers = root_element.selectNodes("//mapper");
        for(Element e:element_mappers){
            String resource = e.attributeValue("resource");
            InputStream in = Resources.getResourceAsStream(resource);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(in);
        }
        return configuration;
    }
}
